﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using VoteSystem.Models;

namespace VoteSystem.Services
{
    public class VoteService
    {
        public List<VoteViewModel> QueryVoteViewModel(string deptName)
        {
            List<VoteViewModel> list = new List<VoteViewModel>();
            try
            {
                using (VoteSystemContext db = new VoteSystemContext())
                {
                    var votePositions = db.EmployeeVotePositions.Where(v => ( v.Position1.DeptName == deptName
                                                                            || v.Position2.DeptName == deptName
                                                                            || v.Position3.DeptName == deptName )
                                                                            && v.Config.Active).ToList();
                    //按岗位id分组数据
                    var allPositions = db.Positions.Where(p => p.DeptName == deptName).ToList(); //本科室所有岗位

                    VoteViewModel vvm = null;
                    foreach (var position in allPositions)
                    {
                        vvm = new VoteViewModel();
                        vvm.PositionId = position.Id;
                        vvm.PositionName = position.PositionName;
                        vvm.DeptName = position.DeptName;
                        //投递该岗位的第1志愿的员工
                        var employeeVotePosition1 = votePositions.Where(v => v.PositionId1 == position.Id).ToList();
                        employeeVotePosition1.ForEach(x => {

                            vvm.EmployeeVote1.Add(new VoteItemViewModel() { EmployeeId = x.EmployeeId, EmployeeName = x.Employee.Name });
                        });

                        //投递该岗位的第2志愿的员工
                        var employeeVotePosition2 = votePositions.Where(v => v.PositionId2 == position.Id).ToList();
                        employeeVotePosition2.ForEach(x => {
                            vvm.EmployeeVote2.Add(new VoteItemViewModel() { EmployeeId = x.EmployeeId, EmployeeName = x.Employee.Name });
                        });
                        //投递该岗位的第3志愿的员工
                        var employeeVotePosition3 = votePositions.Where(v => v.PositionId3 == position.Id).ToList();
                        employeeVotePosition3.ForEach(x => {
                            vvm.EmployeeVote3.Add(new VoteItemViewModel() { EmployeeId = x.EmployeeId, EmployeeName = x.Employee.Name });
                        });
                        list.Add(vvm);
                    }
                    
                }


            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message);
                LogHelper.Error(ex.StackTrace);
            }
            return list;
        }

        public VoteConfig GetCurrentConfig() 
        {
            using (VoteSystemContext db = new VoteSystemContext())
            {
                return db.VoteConfigs.First(c => c.Active); 
            }
        }

        /// <summary>
        /// 查询已定聘人员
        /// </summary>
        /// <returns></returns>
        public dynamic QuerySelectedEmployeeIds()
        {
            //if (HttpContext.Current.Cache["voteresult"] != null)
            //{
            //    return (HashSet<VoteResultDto>)HttpContext.Current.Cache["voteresult"];
            //}

            using (VoteSystemContext db = new VoteSystemContext())
            {
                var result = db.VoteResults.ToList().Select(x => new VoteResultDto { EmployeeId = x.EmployeeId, PositionId = x.PositionId, Round = x.Round });
             //http://118.122.90.47:8091/   HashSet<VoteResultDto> set = new HashSet<VoteResultDto>(result);
             //   if (HttpContext.Current.Cache["voteresult"] == null) 
             //   {
             //       HttpContext.Current.Cache["voteresult"] = set;
             //   }
                return result;
            }
        }

        public OpResult Decide(int positionId, int employeeId, int round)
        {
            OpResult result = new OpResult();
            try
            {

                //if (HttpContext.Current.Cache["voteresult"] != null)
                //{
                //    var set = (HashSet<VoteResultDto>)HttpContext.Current.Cache["voteresult"];
                //    bool inSet = false;
                //    foreach (var item in set)
                //    {
                //        if (item.PositionId == positionId || item.EmployeeId == employeeId) 
                //        {
                //            inSet = true;
                //            item.EmployeeId = employeeId;
                //            item.PositionId = positionId;
                //            item.Round = round;
                //        }
                //    }

                //    if (!inSet) 
                //    {
                //        set.Add(new VoteResultDto() { PositionId = positionId,EmployeeId = employeeId, Round = round});
                //    }
                //}

                using (VoteSystemContext db = new VoteSystemContext())
                {
                    var inDb = db.VoteResults.SingleOrDefault(r => r.Config.Active && (r.PositionId == positionId || r.EmployeeId == employeeId ) && r.Round == round);
                    VoteResult vote = null;
                    if (inDb == null) 
                    {
                        vote = new VoteResult();
                        vote.VoteConfigId = 1;
                        vote.PositionId = positionId;
                        vote.EmployeeId = employeeId;
                        vote.Round = round;
                        db.VoteResults.Add(vote);
                    }
                    else
                    {
                        inDb.EmployeeId = employeeId;
                        inDb.Round = round;
                    }
                    db.SaveChanges();
                    result.IsSuccess = true;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message);
                LogHelper.Error(ex.StackTrace);
                result.IsSuccess = false;
                result.ErrorMessage = "定聘失败！";
            }

            return result;
        }



        public OpResult UnDecide(int positionId, int employeeId, int round) 
        {
            OpResult result = new OpResult();
            result.ErrorMessage = "取消失败,请联系管理员";
            try
            {
                //if (HttpContext.Current.Cache["voteresult"] != null)
                //{
                //    var set = (HashSet<VoteResultDto>)HttpContext.Current.Cache["voteresult"];
                //    for (int i = 0; i < set.Count; i++)
                //    {
                //        var tt = set.ElementAt(i);
                //        if (tt.PositionId == positionId && tt.EmployeeId == employeeId && tt.Round == round) 
                //        {
                //            set.Remove(tt);
                //            break;
                //        }
                //    }
                //}

                using (VoteSystemContext db = new VoteSystemContext())
                {
                    var inDb = db.VoteResults.FirstOrDefault(r => r.Config.Active && r.PositionId == positionId && r.Round == round && r.EmployeeId == employeeId);
                    if (inDb != null) {
                        db.VoteResults.Remove(inDb);
                        db.SaveChanges();
                    }
                }
                result.IsSuccess = true;
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message);
                LogHelper.Error(ex.StackTrace);
                result.IsSuccess = false;
            }

            return result;
        }

        public DataTable QueryResult()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("科室");
            dt.Columns.Add("岗位");
            dt.Columns.Add("定聘职员");
            dt.Columns.Add("联系电话");

            using (VoteSystemContext db = new VoteSystemContext())
            {
                var list = db.VoteResults.OrderBy(v =>v.Position.DeptName).ThenBy(v=>v.Position.PositionName).ToList();
                foreach (var item in list)
                {
                    DataRow row = dt.NewRow();
                    row["科室"] = item.Position.DeptName;
                    row["岗位"] = item.Position.PositionName;
                    row["定聘职员"] = item.Employee.Name;
                    row["联系电话"] = item.Employee.Mobile;
                    dt.Rows.Add(row);
                }
            }
            return dt;
        }

        public DataTable QueryUnSelectedResult()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("落聘人员");
            dt.Columns.Add("联系电话");
            dt.Columns.Add("第一志愿科室");
            dt.Columns.Add("第一志愿岗位");
            dt.Columns.Add("第二志愿科室");
            dt.Columns.Add("第二志愿岗位");
            dt.Columns.Add("第三志愿科室");
            dt.Columns.Add("第三志愿岗位");
            using (VoteSystemContext db = new VoteSystemContext())
            {
                var allSelectedEmployeeId = db.VoteResults.Select(v => v.EmployeeId).ToList();
                var employeeVotePositions = db.EmployeeVotePositions.Where(e => !allSelectedEmployeeId.Contains(e.EmployeeId)).ToList();

                foreach (var item in employeeVotePositions)
                {
                    var row = dt.NewRow();
                    row[0] = item.Employee.Name;
                    row[1] = string.IsNullOrEmpty( item.Employee.Mobile) ? string.Empty : item.Employee.Mobile;
                    row[2] = item.Position1.DeptName;
                    row[3] = item.Position1.PositionName;
                    row[4] = item.Position2.DeptName;
                    row[5] = item.Position2.PositionName;
                    row[6] = item.Position3.DeptName;
                    row[7] = item.Position3.PositionName;

                    dt.Rows.Add(row);
                }
            }

            return dt;
        }
    }

    //public class MyCache 
    //{
    //    public static HashSet<VoteResultDto> ResultCache;
        
    //    static MyCache()
    //    {
    //        ResultCache = new HashSet<VoteResultDto>();
    //    }
    //}
}